package com.listener.dao.impl;

import com.listener.dao.AbilityDao;
import com.listener.pojo.Ability;
import com.listener.pojo.Page;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Repository
public class AbilityDaoImpl implements AbilityDao {
    private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate=jdbcTemplate;
    }
    public List<Ability> selectAllAbility() {
        String sql="select * from ability";
        RowMapper<Ability> rowMapper = new BeanPropertyRowMapper<Ability>(Ability.class);
        return this.jdbcTemplate.query(sql, rowMapper);
    }
    public List<Ability> selectAbility(Ability ability) {
        RowMapper<Ability> rowMapper = new BeanPropertyRowMapper<Ability>(Ability.class);
        String sql="select * from ability where 1=1 ";
        if(ability.getAbility()!=null){
            sql+="and ability='"+ability.getAbility()+"'";
        }
        return this.jdbcTemplate.query(sql,rowMapper);
    }
    public Page<Ability> selectAbilityPage(Ability ability, Integer pageNum, Integer pageSize) {
        Page<Ability> page=new Page<Ability>();
        String sql=" SELECT CEIL(COUNT(*) / ?) as pageSum FROM ability where 1=1 ";
        if(ability.getAbility()!=null){
            sql+="and ability like CONCAT('%"+ability.getAbility()+"%') ";
        }
        if(ability.getDescription()!=null){
            sql+="and description like CONCAT('%"+ability.getDescription()+"%') ";
        }
        RowMapper<Ability> rowMapper = new BeanPropertyRowMapper<Ability>(Ability.class);
        page.setPageSum(Integer.parseInt(this.jdbcTemplate.queryForMap(
                sql,new Object[]{pageSize}).get("pageSum").toString()));
        page.setPageNum(pageNum);
        page.setPageSize(pageSize);
        sql="select * from ability where 1=1 ";
        if(ability.getAbility()!=null){
            sql+="and ability like CONCAT('%"+ability.getAbility()+"%') ";
        }
        if(ability.getDescription()!=null){
            sql+="and description like CONCAT('%"+ability.getDescription()+"%') ";
        }
        sql+=" limit "+(pageNum-1)*pageSize+","+pageSize;
        page.setPage(this.jdbcTemplate.query(sql,rowMapper));
        return page;
    }
}
